import { fixModel } from '@/model/common/kv2str';
import type { ResponseData } from '@/model/common/responsedata';
import router from '@/router';
import { useUserStore } from '@/stores/userInfo';
import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
const axiosInstance: AxiosInstance = axios.create({
  timeout: 100000,
  baseURL: 'api/',
});
// 添加请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    const store = useUserStore();
    if (store.token && store.token.length > 0) {
      config.baseURL = 'api/';
      config.headers['Authorization'] = store.token;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  (error: any) => {
    let msg = '';
    if (error.response && error.response.data) {
      if (error.response.status === 401) {
        router.push('/login');
      }
      const responsedata = error.response.data as ResponseData<string>;
      if (responsedata !== null) {
        msg = responsedata.Message!;
      } else {
        msg = error.response.message;
      }
    } else {
      msg = '网络不可达';
    }
    ElMessage.error(msg);

    return Promise.reject(msg);
  }
);
const post = <T>(url: string, arg?: any) => {
  return new Promise<ResponseData<T>>((resolve, rejects) => {
    fixModel(arg);
    axiosInstance
      .post(url, arg)
      .then((response) => {
        if (response.status === 200) {
          resolve(response.data as ResponseData<T>);
        }
      })
      .catch((err) => {
        rejects(err);
      });
  });
};
const get = <T>(url: string, arg?: any) => {
  return new Promise<ResponseData<T>>((resolve, rejects) => {
    axiosInstance
      .get(url, { params: arg })
      .then((response) => {
        if (response.status === 200) {
          resolve(response.data as ResponseData<T>);
        }
      })
      .catch((err) => {
        rejects(err);
      });
  });
};

export { post, get };
